﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Threading;
using System.Collections.Specialized;

namespace Kokomo
{
	public class DispatcherProjectedList<TItem, TSource> : ProjectedList<TItem, TSource>
	{
		public DispatcherProjectedList(
			IList<TSource> sourceList,
			Func<TSource, TItem> converter,
			Dispatcher dispatcher = null
			)
			: base(sourceList, converter)
		{
			if (dispatcher == null)
				this.Dispatcher = Dispatcher.CurrentDispatcher;
			else
				this.Dispatcher = dispatcher;
		}

		public Dispatcher Dispatcher { get; private set; }

		protected override void OnSourceItemsAdded(System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
		{
			this.Dispatcher.BeginInvoke(
				(Action<NotifyCollectionChangedEventArgs>)base.OnSourceItemsAdded,
				e
				);
		}
		protected override void OnSourceItemsRemoved(NotifyCollectionChangedEventArgs e)
		{
			this.Dispatcher.BeginInvoke(
				(Action<NotifyCollectionChangedEventArgs>)base.OnSourceItemsRemoved,
				e
				);
		}
		protected override void OnSourceItemsMoving(NotifyCollectionChangedEventArgs e)
		{
			this.Dispatcher.BeginInvoke(
				(Action<NotifyCollectionChangedEventArgs>)base.OnSourceItemsMoving,
				e
				);
		}
		protected override void OnSourceItemsReplacing(NotifyCollectionChangedEventArgs e)
		{
			this.Dispatcher.BeginInvoke(
				(Action<NotifyCollectionChangedEventArgs>)base.OnSourceItemsReplacing,
				e
				);
		}
		protected override void OnReset()
		{
			this.Dispatcher.BeginInvoke(
				(Action)base.OnReset
				);
		}
	}
}
